"""
准确率,召回率
"""
from keras.metrics import (Precision, Recall, TruePositives,
                           FalsePositives, FalseNegatives)


def get_data():
    """

    :return:
    """
    y_true = [0, 0, 1, 1]
    y_pred = [0, 0.5, 0.3, 0.9]
    return y_true, y_pred


def compute(y_true, y_pred):
    """
    pre = tp / (tp + fp)
    recall = tp / (tp + fn)
    :param y_true:
    :param y_pred:
    :return:
    """
    tp = TruePositives()
    tp.update_state(y_true=y_true, y_pred=y_pred)
    tp_rs = tp.result().numpy()

    fp = FalsePositives()
    fp.update_state(y_true=y_true, y_pred=y_pred)
    fp_rs = fp.result().numpy()

    fn = FalseNegatives()
    fn.update_state(y_true=y_true, y_pred=y_pred)
    fn_rs = fn.result().numpy()

    # 准确率
    precision = tp_rs / (tp_rs + fp_rs)

    # 召回率
    recall = tp_rs / (tp_rs + fn_rs)

    return precision, recall


def run():
    """
    主程序
    :return:
    """
    y_true, y_pred = get_data()

    y_pred = [1 if ratio >= 0.5 else 0 for ratio in y_pred]

    # 自己计算
    my_precision, my_recall = compute(y_true=y_true, y_pred=y_pred)

    precision = Precision(thresholds=0.5)
    precision.update_state(y_true=y_true, y_pred=y_pred)

    recall = Recall()
    recall.update_state(y_true=y_true, y_pred=y_pred)

    info = 'precision: my: {}, keras: {}\nrecall: my: {}, keras: {}'.\
        format(my_precision, precision.result(), my_recall, recall.result())
    print(info)


if __name__ == '__main__':
    run()
